package com.bw.product.service.impl;

import com.bw.common.security.utils.SecurityUtils;
import com.bw.model.LoginUser;
import com.bw.product.domain.DiscountCoupon;
import com.bw.product.domain.SkuAttrDiscountCoupon;
import com.bw.product.domain.UserAttrDiscountCoupon;
import com.bw.product.domain.vo.SkuAttrDiscountCouponVo;
import com.bw.product.mapper.DiscountCouponMapper;
import com.bw.product.mapper.SkuAttrDiscountCouponMapper;
import com.bw.product.mapper.UserAttrDiscountCouponMapper;
import com.bw.product.service.SkuAttrDiscountCouponService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class SkuAttrDiscountCouponServiceImpl implements SkuAttrDiscountCouponService {
    @Autowired
    private SkuAttrDiscountCouponMapper skuAttrDiscountCouponMapper;
    @Autowired
    private DiscountCouponMapper discountCouponMapper;
    @Autowired
    private UserAttrDiscountCouponMapper userAttrDiscountCouponMapper;

    /**
     * 根据商品skuI获取优惠券
     *
     * @param skuId
     * @return
     */
    @Override
    public List<SkuAttrDiscountCouponVo> selectSkuAttrDiscountCoupon(Long skuId) {

        return skuAttrDiscountCouponMapper.selectSkuAttrDiscountCoupon(skuId);
    }

    /**
     * 用户领取优惠券
     * @param discountCouponId
     */
    @Transactional
    @Override
    public void add(Integer discountCouponId) {
        //获取登录用户信息
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long userid = loginUser.getUserid();
        //获取所有优惠券信息
        DiscountCoupon discountCoupon=discountCouponMapper.selectByDiscountCoupon(discountCouponId);
        if (discountCoupon==null){
            throw  new RuntimeException("优惠券不存在");
        }

        Date now = new Date();
        if(now.before(discountCoupon.getUseStartTime())){
           throw new RuntimeException("优惠券还没到使用时间");
        }


        UserAttrDiscountCoupon userAttrDiscountCoupon = new UserAttrDiscountCoupon();
        userAttrDiscountCoupon.setCouponId(Long.valueOf(discountCouponId));
        userAttrDiscountCoupon.setUserId(userid);
        userAttrDiscountCoupon.setState(0L);
        userAttrDiscountCoupon.setStatus(1L);
        userAttrDiscountCoupon.setDrawTime(new Date());

        //添加
        userAttrDiscountCouponMapper.insert(userAttrDiscountCoupon);

        //修改状态
        skuAttrDiscountCouponMapper.updateBySkuAttrDiscountCoupon(discountCouponId);
    }

    /**
     * 首页优惠券
     * @param skuAttrDiscountCouponVo
     * @return
     */
    @Override
    public List<SkuAttrDiscountCouponVo> list(SkuAttrDiscountCouponVo skuAttrDiscountCouponVo) {
        return skuAttrDiscountCouponMapper.list(skuAttrDiscountCouponVo);
    }


}
